import { NextRequest, NextResponse } from 'next/server';
import { readUsers, writeUsers } from '@/lib/data';
import { verifyToken } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const users = readUsers();
    // 不返回密码
    const usersWithoutPassword = users.map(({ password, ...user }) => user);

    return NextResponse.json({ success: true, users: usersWithoutPassword });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '获取用户列表失败' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');

    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const { searchParams } = new URL(request.url);
    const id = searchParams.get('id');
    let ids: string[] = [];
    if (id) {
      ids = [id];
    } else {
      try {
        const body = await request.json();
        ids = Array.isArray(body?.ids) ? body.ids.filter((x: any) => typeof x === 'string') : [];
      } catch {}
    }

    if (!ids.length) {
      return NextResponse.json(
        { success: false, message: '缺少要删除的用户ID' },
        { status: 400 }
      );
    }

    const before = readUsers();

    // 规则：至少保留一个管理员
    const adminIds = before.filter(u => u.isAdmin).map(u => u.id);
    const adminCount = adminIds.length;
    const adminsToDelete = adminIds.filter(id0 => ids.includes(id0)).length;

    if (adminCount > 0 && adminsToDelete >= adminCount) {
      return NextResponse.json(
        { success: false, message: '至少保留一个管理员账户，无法删除最后一个管理员' },
        { status: 400 }
      );
    }

    const after = before.filter(u => !ids.includes(u.id));
    writeUsers(after);
    return NextResponse.json({ success: true, deleted: before.length - after.length });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '删除用户失败' },
      { status: 500 }
    );
  }
}

